/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.vincent.filepicker.video;

import com.vincent.filepicker.ResourceTable;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.global.resource.RawFileDescriptor;
import ohos.media.common.Source;
import ohos.media.photokit.metadata.AVStorage;
import ohos.media.player.Player;
import ohos.utils.net.Uri;

/**
 * Video playback
 */
public class VideoAbility extends Ability {

    private static Player mPlayer;
    private SurfaceProvider mSurfaceProvider;
    private long mVideoId;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_video);
        mVideoId = intent.getLongParam("videoId", 0);
    }

    @Override
    protected void onActive() {
        super.onActive();
        initSurfaceProvider();
    }

    private void initSurfaceProvider() {
        mSurfaceProvider = (SurfaceProvider) findComponentById(ResourceTable.Id_surfaceProvider);
        mPlayer = new Player(this);
        mSurfaceProvider.getSurfaceOps().get().addCallback(new VideoSurfaceCallback());
        mSurfaceProvider.pinToZTop(true);
    }

    class VideoSurfaceCallback implements SurfaceOps.Callback {

        @Override
        public void surfaceCreated(SurfaceOps surfaceOps) {

            if (mSurfaceProvider.getSurfaceOps().isPresent()) {
                Surface surface = mSurfaceProvider.getSurfaceOps().get().getSurface();
//                playUrl(surface);
//                playLocalFile(surface);
                playExternalStorageFile(surface);
            }
        }

        @Override
        public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {

        }

        @Override
        public void surfaceDestroyed(SurfaceOps surfaceOps) {
            System.out.println("surfaceDestroyed() called.");
        }

    }

    public class VideoPlayerCallback implements Player.IPlayerCallback {

        @Override
        public void onPrepared() {
            System.out.println("onPrepared");
        }

        @Override
        public void onMessage(int i, int i1) {

            System.out.println("onMessage");
        }

        @Override
        public void onError(int i, int i1) {

            System.out.println("onError: i=" + i + ", i1=" + i1);
        }

        @Override
        public void onResolutionChanged(int i, int i1) {

            System.out.println("onResolutionChanged");
        }

        @Override
        public void onPlayBackComplete() {

            System.out.println("onPlayBackComplete");
            if (mPlayer != null) {
                mPlayer.stop();
                mPlayer = null;
            }
        }

        @Override
        public void onRewindToComplete() {

            System.out.println("onRewindToComplete");
        }

        @Override
        public void onBufferingChange(int i) {

            System.out.println("onBufferingChange");
        }

        @Override
        public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {
            System.out.println("onNewTimedMetaData");
        }

        @Override
        public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {
            System.out.println("onMediaTimeIncontinuity");
        }
    }

    /**
     * 本地资源视频
     *
     * @param surface
     */
    private void playLocalFile(Surface surface) {
        try {
            RawFileDescriptor filDescriptor = getResourceManager().getRawFileEntry("resources/rawfile/abc.mp4").openRawFileDescriptor();
            Source source = new Source(filDescriptor.getFileDescriptor(), filDescriptor.getStartPosition(), filDescriptor.getFileSize());
            mPlayer.setSource(source);
            mPlayer.setVideoSurface(surface);
            mPlayer.setPlayerCallback(new VideoPlayerCallback());
            mPlayer.prepare();
            mSurfaceProvider.setTop(0);
            mPlayer.play();
        } catch (Exception e) {
            System.out.println("playUrl Exception:" + e.getMessage());
        }
    }

    /**
     * 系统文件读取的视频
     *
     * @param surface
     */
    private void playExternalStorageFile(Surface surface) {
        try {
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Video.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(mVideoId));
            DataAbilityHelper helper = DataAbilityHelper.creator(this);
            mPlayer.setSource(new Source(helper.openFile(uri, "r")));
            mPlayer.setVideoSurface(surface);
            mPlayer.setPlayerCallback(new VideoPlayerCallback());
            mPlayer.prepare();
            mSurfaceProvider.setTop(0);
            mPlayer.play();
        } catch (Exception e) {
            System.out.println("playUrl Exception:" + e.getMessage());
        }


    }

    /**
     * 网络视频
     *
     * @param surface
     */
    private void playUrl(Surface surface) {
        try {
            Source source = new Source("video url");
            mPlayer.setSource(source);
            mPlayer.setVideoSurface(surface);
            mPlayer.setPlayerCallback(new VideoPlayerCallback());
            mPlayer.prepare();
            mSurfaceProvider.setTop(0);
            mPlayer.play();
        } catch (Exception e) {
            System.out.println("playUrl Exception:" + e.getMessage());
        }
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
        if (null != mPlayer) {
            mPlayer.release();
        }
    }
}
